package com.giantlizard.cloud.base.json;

import com.giantlizard.cloud.base.enums.HttpStatusCodeEnum;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;

import java.io.Serializable;

/**
 * 统一响应返回体
 * @param <T>
 */
@Data
@AllArgsConstructor
@Builder
public class ResponseResult<T> implements Serializable {
    private static final long serialVersionUID = 1L;

    /**
     * HTTP状态码
     */
    private Integer code;

    /**
     * 消息
     */
    private String msg;

    /**
     * 数据
     */
    @Builder.Default
    private T data = null;

    /**
     * 构造函数，初始化默认成功状态
     */
    public ResponseResult() {
        this.code = HttpStatusCodeEnum.SUCCESS.getCode();
        this.msg = HttpStatusCodeEnum.SUCCESS.getMsg();
    }

    public ResponseResult(int code, String msg) {
        this.code = code;
        this.msg = msg;
    }


    /**
     * 创建错误响应结果
     *
     * @param code 错误码
     * @param msg  错误消息
     * @return ResponseResult
     */
    public static <T> ResponseResult<T> errorResult(int code, String msg) {
        return new ResponseResult<>(code, msg);
    }

    /**
     * 创建成功响应结果，无数据
     *
     * @return ResponseResult
     */
    public static <T> ResponseResult<T> okResult() {
        return new ResponseResult<>();
    }

    /**
     * 创建成功响应结果，自定义状态码和消息
     *
     * @param code 状态码
     * @param msg  消息
     * @return ResponseResult
     */
    public static <T> ResponseResult<T> okResult(int code, String msg) {
        return new ResponseResult<>(code, msg);
    }

    /**
     * 创建成功响应结果，携带数据
     *
     * @param data 数据
     * @return ResponseResult
     */
    public static <T> ResponseResult<T> okResult(T data) {
        ResponseResult<T> result = new ResponseResult<>();
        result.setData(data);
        return result;
    }

    /**
     * 创建错误响应结果，基于枚举
     *
     * @param enums 枚举
     * @return ResponseResult
     */
    public static <T> ResponseResult<T> errorResult(HttpStatusCodeEnum enums) {
        return new ResponseResult<>(enums.getCode(), enums.getMsg());
    }

    /**
     * 创建错误响应结果，基于枚举和自定义消息
     *
     * @param enums 枚举
     * @param msg   自定义消息
     * @return ResponseResult
     */
    public static <T> ResponseResult<T> errorResult(HttpStatusCodeEnum enums, String msg) {
        return new ResponseResult<>(enums.getCode(), msg);
    }

    /**
     * 设置HTTP状态码枚举，创建响应结果
     *
     * @param enums 枚举
     * @return ResponseResult
     */
    public static <T> ResponseResult<T> setHttpCodeEnum(HttpStatusCodeEnum enums) {
        return new ResponseResult<>(enums.getCode(), enums.getMsg());
    }

    /**
     * 设置HTTP状态码枚举和自定义消息，创建响应结果
     *
     * @param enums 枚举
     * @param msg   自定义消息
     * @return ResponseResult
     */
    private static <T> ResponseResult<T> setHttpCodeEnum(HttpStatusCodeEnum enums, String msg) {
        return new ResponseResult<>(enums.getCode(), msg);
    }
}
